package com.frogs.ucenter.service.impl;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.jsoup.Connection.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.PageTurn;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.web.api.entity.ApiUrl;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.api.response.Response.ResultParamEnum;
import com.frogs.ucenter.entity.UserRechargeRecord;
import com.frogs.ucenter.service.AbsService;
import com.frogs.ucenter.service.UserRechargeService;

@Service("userRechargeRecordService")
public class UserRechargeServiceImpl extends AbsService implements UserRechargeService {
	
	private static Logger log = LoggerFactory.getLogger(UserRechargeServiceImpl.class);
	
	/**
	 * 创建一条充值记录
	 */
	@Override
	public UserRechargeRecord addUserRechargeRecord(Integer userId, BigDecimal rechargeMoney, String rechargeCard, String rechargeFrom, String verify) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_RECHARGE_ADD");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.rechargeMoney.getParamName(), rechargeMoney.toString(),
				ApiUrlParamEnum.rechargeCard.getParamName(), rechargeCard, 
				ApiUrlParamEnum.rechargeFrom.getParamName(), rechargeFrom,
				ApiUrlParamEnum.verify.getParamName(), verify };
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() == result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName())) {
				UserRechargeRecord userRechargeRecord = result.getJSONObject("response").getObject("info", UserRechargeRecord.class);
				return userRechargeRecord;
			}
		} catch (IllegalStateException e) {
			log.error("func[addUserRechargeRecord] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} catch(Exception e){
			throw new Exception("创建充值记录接口请求失败！");
		}
		return null;
	}
	
	/**
	 * 更新充值记录
	 */
	@Override
	public UserRechargeRecord updateUserRechargeRecord(Integer recordId, Integer userId, BigDecimal rechargeMoney, String rechargeCard, String rechargeFrom, String verify) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_RECHARGE_UPDATE");
		String[] otherParams = {ApiUrlParamEnum.recordId.getParamName(), recordId.toString(),
				ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.rechargeMoney.getParamName(), rechargeMoney.toString(),
				ApiUrlParamEnum.rechargeCard.getParamName(), rechargeCard, 
				ApiUrlParamEnum.rechargeFrom.getParamName(), rechargeFrom,
				ApiUrlParamEnum.verify.getParamName(), verify };
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() == result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName())) {
				UserRechargeRecord userRechargeRecord = result.getJSONObject("response").getObject("info", UserRechargeRecord.class);
				return userRechargeRecord;
			}
		} catch (IllegalStateException e) {
			log.error("func[updateUserRechargeRecord] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} catch(Exception e){
			throw new Exception("更新充值记录接口请求失败！");
		}
		return null;
	}
	
	/**
	 * 获取充值记录列表
	 */
	@Override
	public PageList<Map<String,Object>> getUserRechargeRecordList(Integer userId, Integer pageNo, Integer pageSize, String verify) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_RECHARGE_LIST");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.pageNo.getParamName(), pageNo.toString(),
				ApiUrlParamEnum.pageSize.getParamName(), pageSize.toString(), 
				ApiUrlParamEnum.verify.getParamName(), verify };
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		PageList<Map<String,Object>> result = new PageList<Map<String,Object>>();
		JSONObject jsonObjectResult = null;
		try{
			jsonObjectResult = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() == jsonObjectResult.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName())) {
				List<Map<String, Object>> list = jsonObjectResult.getJSONObject("response").getObject("list", List.class);
				result.addAll(list);
				
		    	JSONObject pageTurnJSONObject = jsonObjectResult.getJSONObject("response").getJSONObject("pageTurn");
		    	result.setPageTurn(JSON.toJavaObject(pageTurnJSONObject, PageTurn.class));
			}
		} catch (IllegalStateException e) {
			log.error("func[getUserRechargeRecordList] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} catch(Exception e){
			throw new Exception("获取充值记录列表接口请求失败！");
		}
		return result;
	}
	
	/**
	 * 获取充值记录信息
	 */
	@Override
	public UserRechargeRecord getUserRechargeRecordInfo(Integer userId, Integer recordId, String verify) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_RECHARGE_INFO");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.recordId.getParamName(), recordId.toString(),
				ApiUrlParamEnum.verify.getParamName(), verify };
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		UserRechargeRecord userRechargeRecord = null;
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() == result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName())) {
				userRechargeRecord = result.getJSONObject("response").getObject("info", UserRechargeRecord.class);
			}
		} catch (IllegalStateException e) {
			log.error("func[getUserRechargeRecordInfo] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} catch(Exception e){
			throw new Exception("获取充值记录接口请求失败！");
		}
		return userRechargeRecord;
	}
	
	/**
	 * 获取用户余额
	 */
	@Override
	public String getUserBalanceInfo(Integer userId, String verify) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_RECHARGE_BALANCE_SHOW");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.verify.getParamName(), verify };
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		
		JSONObject result = null;
		String userRechargeBalance = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() == result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName())) {
				userRechargeBalance = result.getJSONObject("response").getString("info");
			}
		} catch (IllegalStateException e) {
			log.error("func[getUserRechargeRecordInfo] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} catch(Exception e){
			throw new Exception("获取用户余额接口请求失败！");
		}
		return userRechargeBalance;
	}
	
	/**
	 * 获取余额消费记录列表
	 */
	@Override
	public PageList<Map<String,Object>> getUserConsumeRecordList(Integer userId, Integer pageNo, Integer pageSize, String verify) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_RECHARGE_CONSUME_RECORD_LIST");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.pageNo.getParamName(), pageNo.toString(),
				ApiUrlParamEnum.pageSize.getParamName(), pageSize.toString(), 
				ApiUrlParamEnum.verify.getParamName(), verify };
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		PageList<Map<String,Object>> result = new PageList<Map<String,Object>>();
		JSONObject jsonObjectResult = null;
		try{
			jsonObjectResult = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() == jsonObjectResult.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName())) {
				List<Map<String, Object>> list = jsonObjectResult.getJSONObject("response").getObject("list", List.class);
				result.addAll(list);
				
		    	JSONObject pageTurnJSONObject = jsonObjectResult.getJSONObject("response").getJSONObject("pageTurn");
		    	result.setPageTurn(JSON.toJavaObject(pageTurnJSONObject, PageTurn.class));
			}
		} catch (IllegalStateException e) {
			log.error("func[getUserConsumeRecordList] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} catch(Exception e){
			throw new Exception("获取余额消费记录列表接口请求失败！");
		}
		return result;
	}
	
	/**
	 * 验证用户余额
	 */
	@Override
	public Boolean verifyUserBalance(Integer userId, String verify) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_RECHARGE_BALANCE_VERIFY");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.verify.getParamName(), verify };
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() == result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName())) {
				return true;
			}
		} catch (IllegalStateException e) {
			log.error("func[getUserRechargeRecordInfo] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} catch(Exception e){
			throw new Exception("验证用户余额接口请求失败！");
		}
		return false;
	}
}
